﻿#region Copyright and Licensing Notice
// Copyright (C) 2011 Steven Bosnick
// 
// This program is open source software; you can redistribute it 
// and/or modifiy it under the terms of the Eclipse Public License,
// version 1.0.
// 
// This program is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A 
// PARTICULAR PURPOSE. See the Eclipse Public License for more
// details.
// 
// You should have received a copy of the Eclipse Public License 
// along with this program; if not, you can find a copy at
// "http://www.opensource.org/licenses/eclipse-1.0.php".
#endregion
using System;
using System.Threading.Tasks;
using BitwiseOre.SharedMemory.Core.Common;

namespace BitwiseOre.SharedMemory.Core
{
    internal sealed class Connector : IConnector
    {
        private readonly IListenerQueue _queue;
        private readonly IEventWaitHandleFactory _eventFactory;
        private readonly Func<Guid> _guidFactory;

        public Connector(IListenerQueue queue, IEventWaitHandleFactory eventFactory, Func<Guid> guidFactory)
        {
            _queue = queue;
            _eventFactory = eventFactory;
            _guidFactory = guidFactory;
        }

        public Task<T> Connect<T>(TimeSpan timeOut, Func<Guid, T> factory)
        {
            var guid = _guidFactory();
            var eventhandle = _eventFactory.Create(guid.ToString());
            try
            {
                _queue.Enqueue(guid);

                return eventhandle.Value.Wait(timeOut)
                    .Then(() => factory(guid))
                    .Finally(eventhandle.Dispose);
            }
            catch 
            {
                eventhandle.Dispose();
                throw;
            }
        }
    }
}